package com.atguigu.spzx.manager.service.impl;

import com.atguigu.spzx.manager.config.MinioProperties;
import com.atguigu.spzx.manager.service.FileService;
import com.atguigu.spzx.model.exception.GuiguException;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * @author LT
 * @create 2024-03-13-20:51
 */
@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file, String module) {
        if (file.isEmpty()){
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        try {
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."));

            filename = module +new DateTime().toString("/yyyy-MM-dd/")+System.currentTimeMillis()+"_"+ UUID.randomUUID().toString().replace("-","").substring(0,8)+suffix;

            MinioClient client = MinioClient.builder()
                    .endpoint(MinioProperties.ENDPOINT)
                    .credentials(MinioProperties.ACCESS_KEY,MinioProperties.SECRET_KEY)
                    .build();

            client.putObject(PutObjectArgs.builder()
                            .bucket(MinioProperties.BUCKET)
                            .stream(file.getInputStream(),file.getSize(),-1)
                            .object(filename)
                            .build());
            String path = MinioProperties.ENDPOINT+"/"+MinioProperties.BUCKET+"/"+filename;
            System.out.println(path);
            return path;
        } catch (Exception e){
            throw new GuiguException(ResultCodeEnum.FILE_UPLOAD_ERROR,e);
        }
    }

    @Override
    public void deleteFile(String path) {
        try {
            //1、创建minio客户端对象
            MinioClient client = MinioClient.builder()
                    .endpoint(MinioProperties.ENDPOINT) //minio服务器地址
                    .credentials(MinioProperties.ACCESS_KEY, MinioProperties.SECRET_KEY) //minio账号密码
                    .build();
            //2、删除
            path = path.substring((MinioProperties.ENDPOINT+"/"+MinioProperties.BUCKET+"/").length());
            client.removeObject(RemoveObjectArgs.builder()
                    .bucket(MinioProperties.BUCKET)
                    .object(path)
                    .build());
        } catch (Exception e) {
            throw new GuiguException(ResultCodeEnum.FILE_DELETE_ERROR,e);
        }
    }

}
